// 导入用户集合
const { User } = require('../../../model/user');
const { generateToken } = require('../../../middleGuard/jwt.js')
const aixos = require('axios')

module.exports = async (req, res) => {
  const { code, userInfo } = req.body
  console.log('body', req.body)
  if (code) {
    const AppID = 'wx18d3aa8fd9016d27'
    const AppSecret = '5d27faf4ed931b5e86921b1d32e0c65d'
    aixos.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${AppID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`).then(async (res2) => {
      console.log('res2', res2.data)
      const data = res2.data
      const user = await User.findOne({ openid: data.openid })
      if (!user) {
        // 无当前微信用户，自动创建
        // 微信登录，自动注册
        User.create({
          openid: data.openid,
          avatar: userInfo.avatarUrl,
          nickname: userInfo.nickName
        }).then(item => {
          console.log('item', item)
          res.json({
            data: {
              ...item.toObject(),
              token: generateToken({ userId: item._id })
            },
            message: '创建用户成功！'
          })
        }).catch((err) => {
          res.status(403)
          res.json({
            log: err,
            message: '用户创建失败！' + err
          })
        })
      } else {
        const { _id, username, nickname, avatar, roleType } = user
        res.json({
          data: {
            _id, username, nickname, avatar, roleType,
            token: generateToken({ userId: user._id })
          },
          message: '登录成功！'
        })
      }
    }).catch(err => {
      console.log('err', err)
      res.json({
        message: err
      })
    })
  }
  // session_key: 'CxYK3kiBwkkmOVQ3qw8ERQ==',
  // openid: 'o5ms75CpL2RB43Hzj9mURDzYWbH4',
  // unionid: 'oePpl5ysOuDQOQ1PF2bB1viJT16o'
  // const token = generateToken({userId: item._id})
}